﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PC.AzureMultiApp.Storage;
using PC.AzureMultiApp.Core;
using PC.AzureMultiApp.Core.Models;
using PC.AzureMultiApp.Core.Helpers;
using PC.AzureMultiApp.Core.Applications;
using PC.AzureMultiApp.WebRoleMultiApp.Helpers;

namespace PC.AzureMultiApp.WebRoleMultiApp.Controllers
{
    [ValidaAdminRole()]  
    public class UpdateController : Controller
    {
        public ActionResult Update(string id)
        {
            return View(Applications.GetById(id));
        }

        [HttpPost]
        public ActionResult Update(string id, ApplicationModel app)
        {
            ApplicationDataSource dataSource = new ApplicationDataSource();

            ApplicationModel previousValues = Applications.GetById(id);

            if (previousValues != null)
            {
                // Partial update do not update database with new Url. This Url is only for update
                string url = app.ApplicationUrl;
                if (app.PartialUpdate)
                    url = previousValues.ApplicationUrl;

                AzureApplicationEntity updateApp = new AzureApplicationEntity()
                {
                    ApplicationName = previousValues.ApplicationName,
                    ApplicationUrl = url,
                    IsWebDeploy = previousValues.IsWebDeploy,
                    BlobUrl = app.BlobUrl,
                    Name = app.Name,
                    Label = app.Label,
                    Version = app.Version,
                    Status = GlobalDef.Updating,
                    UniqueId = id,

                };

                dataSource.Update(id, updateApp);

                updateApp.ApplicationUrl = app.ApplicationUrl;
                DeploymentManager.Notify(Conversions.GetApplicationModel(updateApp), app.PartialUpdate);
            }

            return RedirectToAction("Application", "Application");
        }

     
    }
}
